import React, { useEffect, useState } from "react";
import {
  Button,
  Card,
  Divider,
  Dropdown,
  Input,
  Menu,
  message,
  Modal,
  Select,
  Typography,
  Upload,
} from "antd";
import {
  DeleteOutlined,
  FileOutlined,
  InboxOutlined,
  MoreOutlined,
  PlusOutlined,
} from "@ant-design/icons";
import { useNavigate } from "react-router-dom";
import type { UploadFile } from "antd/es/upload/interface";
import {
  getAllTenders,
  deleteTenderRecord,
} from "../../api/tendering/tenderApi";
import { createTenderRecord } from "../../api/tendering/uploadApi";

const { Title } = Typography;

interface BiddingItem {
  id: string;
  category: string;
  time: string;
}

const productOptions = [
  { label: "海运", value: "海运" },
  { label: "PP管件", value: "PP管件" },
  { label: "电气材料", value: "电气材料" },
  { label: "钢材", value: "钢材" },
];

const BiddingPage: React.FC = () => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [newQuarter, setNewQuarter] = useState("");
  const [newCategory, setNewCategory] = useState("");
  const [biddings, setBiddings] = useState<BiddingItem[]>([]);
  const navigate = useNavigate();
  const [newFile, setNewFile] = useState<File | null>(null);
  const [fileList, setFileList] = useState<UploadFile[]>([]);

  const showCreateModal = () => {
    setIsModalVisible(true);
  };

  const handleCreateBidding = async () => {
    if (!newQuarter.trim()) {
      message.error("季度不能为空！");
      return;
    }
    if (!newCategory.trim()) {
      message.error("产品类不能为空！");
      return;
    }
    if (!newFile) {
      message.error("请上传报价单 Excel 文件！");
      return;
    }

    try {
      const response = await createTenderRecord(
        newCategory,
        newQuarter,
        newFile
      );
      console.log("Create response:", response.id);
      message.success("招标记录创建成功！");
      setIsModalVisible(false);
      setNewCategory("");
      setNewQuarter("");
      setNewFile(null);
      // 新建成功后根据产品类跳转
      if (newCategory === "海运") {
        navigate(`/summary/sea-transport/${response.id}`);
      } else if (newCategory === "PP管件") {
        navigate(`/summary/pipe-fitting/${response.id}`);
      } else if (newCategory === "电气材料") {
        navigate(`/summary/electrical-material/${response.id}`);
      } else if (newCategory === "钢材") {
        navigate(`/summary/steel/${response.id}`);
      }
    } catch (err: any) {
      console.error("Error in handleCreateBidding:", err);

      if (err.response) {
        const errorMsg =
          err.response.data?.message || "服务器返回错误，请稍后重试！";
        message.error(errorMsg);
      } else if (err.request) {
        message.error("网络请求失败，请检查您的网络连接！");
      } else {
        message.error("创建过程中发生错误，请稍后重试！");
      }
    }
  };

  const handleFileChange = (info: {
    file: UploadFile;
    fileList: UploadFile[];
  }) => {
    setFileList(info.fileList);
    if (info.fileList.length > 0 && info.fileList[0].originFileObj) {
      setNewFile(info.fileList[0].originFileObj as File);
    } else {
      setNewFile(null);
    }
  };

  const handleCancel = () => {
    setIsModalVisible(false);
    setNewCategory("");
    setNewQuarter("");
    setNewFile(null);
    setFileList([]);
  };

  async function removeBidding(id: string) {
    try {
      return await deleteTenderRecord(id);
    } catch (err) {
      console.error("Error in removeBidding:", err);
      throw err;
    }
  }

  const handleBiddingClick = (id: string, category?: string) => {
    if (category === "海运") {
      navigate(`/summary/sea-transport/${id}`);
    } else if (category === "PP管件") {
      navigate(`/summary/pipe-fitting/${id}`);
    } else if (category === "电气材料") {
      navigate(`/summary/electrical-material/${id}`);
    } else if (category === "钢材") {
      navigate(`/summary/steel/${id}`);
    }
  };

  const getAllBiddings = async () => {
    try {
      const response = await getAllTenders();
      // 兼容API返回数组或对象
      const records = Array.isArray(response)
        ? response
        : response.tenders || [];
      const transformedBiddings: BiddingItem[] = records.map((record: any) => ({
        id: record.id,
        category: record.category,
        time: record.quarter,
      }));

      setBiddings(transformedBiddings);
    } catch (err) {
      console.error("Failed to fetch biddings:", err);
      setBiddings([]);
    }
  };

  const handleDeleteBidding = async (id: string) => {
    Modal.confirm({
      title: "确认删除",
      content: "确定要删除这个记录吗？此操作不可恢复。",
      okText: "确认",
      cancelText: "取消",
      async onOk() {
        try {
          await removeBidding(id);
          message.success("删除成功！");
          await getAllBiddings();
        } catch (err) {
          message.error("删除失败，请稍后重试！");
          console.error("删除错误:", err);
        }
      },
    });
  };

  useEffect(() => {
    getAllBiddings();
  }, []);

  return (
    <div
      style={{
        padding: "24px",
        backgroundColor: "white",
        width: "96vw",
        height: "95vh",
        zIndex: 0,
      }}
    >
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
        }}
      >
        <Title level={2}>欢迎使用 招标汇总</Title>
      </div>

      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          marginTop: "16px",
        }}
      >
        <Title level={4}>我的招标记录</Title>
        <div style={{ display: "flex", alignItems: "center", gap: "16px" }}>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={showCreateModal}
          >
            新建
          </Button>
        </div>
      </div>

      <Divider />

      <div
        style={{
          marginTop: "24px",
          display: "grid",
          gridTemplateColumns: "repeat(auto-fill, minmax(250px, 1fr))",
          gap: "16px",
        }}
      >
        {biddings.map((bidding) => (
          <Card
            key={bidding.id}
            style={{ borderRadius: "10px" }}
            title={<FileOutlined />}
            hoverable
            extra={
              <Dropdown
                overlay={
                  <Menu>
                    <Menu.Item
                      key="1"
                      onClick={() => {
                        handleDeleteBidding(bidding.id);
                      }}
                    >
                      <DeleteOutlined /> 删除
                    </Menu.Item>
                  </Menu>
                }
                trigger={["click"]}
              >
                <Button type="text" icon={<MoreOutlined />} />
              </Dropdown>
            }
          >
            <div
              onClick={() => handleBiddingClick(bidding.id, bidding.category)}
              style={{ cursor: "pointer" }}
            >
              <Card.Meta
                title={<h3>{bidding.time}</h3>}
                description={bidding.category}
              />
            </div>
          </Card>
        ))}
      </div>
      <Modal
        title="新建投标"
        open={isModalVisible}
        onOk={handleCreateBidding}
        onCancel={handleCancel}
        okText="创建"
        cancelText="取消"
      >
        <div style={{ maxWidth: 420, margin: "0 auto" }}>
          <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
            <div style={{ display: "flex", alignItems: "center" }}>
              <span
                style={{
                  width: 72,
                  textAlign: "right",
                  marginRight: 12,
                  color: "#666",
                }}
              >
                季度：
              </span>
              <Input
                placeholder="请输入季度"
                value={newQuarter}
                onChange={(e) => setNewQuarter(e.target.value)}
                style={{ flex: 1 }}
              />
            </div>
            <div style={{ display: "flex", alignItems: "center" }}>
              <span
                style={{
                  width: 72,
                  textAlign: "right",
                  marginRight: 12,
                  color: "#666",
                }}
              >
                产品类：
              </span>
              <Select
                style={{ flex: 1 }}
                placeholder="请选择产品类"
                value={newCategory}
                onChange={(value) => setNewCategory(value)}
                options={productOptions}
              />
            </div>
            <div>
              <Upload.Dragger
                accept=".xlsx, .xls"
                maxCount={1}
                beforeUpload={(file) => {
                  const isXlsx =
                    file.type ===
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                  const isXls = file.type === "application/vnd.ms-excel";
                  if (!isXlsx && !isXls) {
                    message.error("只能上传 .xlsx 或 .xls 文件");
                    return Upload.LIST_IGNORE;
                  }
                  return false;
                }}
                onChange={handleFileChange}
                onRemove={() => {
                  setNewFile(null);
                  setFileList([]);
                }}
                fileList={fileList}
              >
                <p className="ant-upload-drag-icon">
                  <InboxOutlined />
                </p>
                <p className="ant-upload-text">
                  点击或拖拽上传 Excel 模板文件（.xlsx, .xls）
                </p>
              </Upload.Dragger>
            </div>
          </div>
        </div>
      </Modal>
    </div>
  );
};

export default BiddingPage;
